package com.example.live.view

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.CountDownTimer
import android.view.Gravity
import android.view.Gravity.BOTTOM
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.PopupWindow
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.app.RouterPath
import com.example.common.mvi.BaseMviActivity
import com.example.image.glide.GlideImgLoader
import com.example.live.R
import com.example.live.adapter.GoodsAdapter
import com.example.live.adapter.RankPageAdapter
import com.example.live.databinding.ActivityLiveRoomBinding
import com.example.live.entity.GoodsEntity
import com.example.live.entity.LiveEntityItem
import com.example.live.intent.LiveViewIntent
import com.example.live.state.LiveUiState
import com.example.live.vm.LiveViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@AndroidEntryPoint
@Route(path = RouterPath.PATH_LIVE_ROOM_PAGE)
class LiveRoomActivity : BaseMviActivity<ActivityLiveRoomBinding>() {
    @Autowired
    lateinit var video: LiveEntityItem
    lateinit var countDownTimer: CountDownTimer
    lateinit var exoPlayer: ExoPlayer
    var time = 0L
    var favNum = 200

    var popupWindow: PopupWindow? = null
    lateinit var goodsAdapter:GoodsAdapter
    private val mViewModel: LiveViewModel by viewModels()
    lateinit var rankPageAdapter: RankPageAdapter

    override fun getLayoutId(): Int =R.layout.activity_live_room

    override fun initViews() {
        ARouter.getInstance().inject(this)
        mDataBinding.liveDetailClose.setOnClickListener {
            finish()
        }
        goodsAdapter=GoodsAdapter()
        // 1. 初始化 ExoPlayer
        exoPlayer = ExoPlayer.Builder(this).build()
        exoPlayer.repeatMode = Player.REPEAT_MODE_ALL
        // 2. 绑定 PlayerView
        mDataBinding.playerView.player = exoPlayer
        // 3. 设置媒体资源（URL 或本地文件）
        val mediaItem = MediaItem.fromUri(video.videopath) // 替换为你的视频URL
        exoPlayer.setMediaItem(mediaItem)
        exoPlayer.prepare()
        exoPlayer.play() // 自动播放
        mDataBinding.liveDetailAuthorName.text = video.name
        GlideImgLoader.loadCircleImage(this, video.avatar_url, mDataBinding.liveDetailAuthorIcon)
//红包倒计时
        countDownTimer = object : CountDownTimer(80000, 1000) {
            override fun onTick(p0: Long) {
                time = p0
                val simpleDateFormat = SimpleDateFormat("mm:ss")
                val s = simpleDateFormat.format(p0)
                mDataBinding.redEnvelopeTime.text = s
            }

            override fun onFinish() {
                mDataBinding.redEnvelopeTime.visibility = View.GONE
                mDataBinding.redEnvelope.visibility = View.GONE
            }
        }.start()

        //红包dialog
        mDataBinding.redEnvelope.setOnClickListener {
            val dialog = RedEnvelopeDialog(this)
            dialog.setTime(time)
            dialog.show()
        }
        //点击弹出购物车列表
        mDataBinding.openGoods.setOnClickListener {
            showPopupWindow(it)
        }
        mDataBinding.hourList.setOnClickListener {
            getShop()
        }
    }

    private fun showPopupWindow(it: View?) {
        val inflater = LayoutInflater.from(this)
        val popupView = inflater.inflate(R.layout.item_goos_dialog, null)
        val width = ViewGroup.LayoutParams.MATCH_PARENT
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        popupWindow = PopupWindow(popupView, width, height).apply {
            // 设置背景，这是点击外部关闭弹窗的必要条件
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            // 设置是否可点击
            isFocusable = true
            // 设置点击外部是否关闭
            isOutsideTouchable = true
            // 设置动画效果
            animationStyle = R.style.BottomSheetDialog
        }
        lifecycleScope.launch {
            mViewModel.channel.send(LiveViewIntent.LoadGoodsInfo(0,1,10,"2"))
        }
        popupView.findViewById<RecyclerView>(R.id.rv_goods).apply {
            adapter = goodsAdapter
            layoutManager = LinearLayoutManager(this@LiveRoomActivity)
        }
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/live/LiveGoodsActivity")
                .withSerializable("goods",adapter.data[position] as GoodsEntity)
                .navigation()
        }
        popupWindow?.showAtLocation(it, BOTTOM, 0, 0)
    }

    private fun getShop() {
        val inflate = LayoutInflater.from(this)
            .inflate(R.layout.item_rankinglist, null)
        val popupWindow = PopupWindow(this)
        popupWindow.contentView = inflate
        popupWindow.width = WindowManager.LayoutParams.MATCH_PARENT
        popupWindow.height = WindowManager.LayoutParams.WRAP_CONTENT
        popupWindow.isFocusable = true
        popupWindow.isOutsideTouchable = true

        val tab = inflate.findViewById<TabLayout>(R.id.ranking_Tab)
        val vp2 = inflate.findViewById<ViewPager2>(R.id.ranking_vp2)
        val fragments = mutableListOf(
            AllFragment(),
            UserFragment()
        )
        val tabs = listOf("全站","带货榜")
        rankPageAdapter = RankPageAdapter(this@LiveRoomActivity,fragments)
        vp2.adapter = rankPageAdapter
        TabLayoutMediator(tab,vp2){tab,position ->
            tab.text = tabs[position]
        }.attach()

        popupWindow.showAtLocation(inflate, Gravity.BOTTOM,0,0)
    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collect{
            when(it){
                is LiveUiState.LoadGoodsInfoSuccess -> {
                    goodsAdapter.addData(it.list)
                    goodsAdapter.notifyDataSetChanged()
                }
                else->{}
            }
        }
    }
}